package com.kingtao.util;

import com.kingtao.entry.LogEntry;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: kingtao
 * @Date: 2023-06-11-15:47
 * @Description:
 */
public class Sha256Util {

    /**
     * 利用java原生的类实现SHA256加密
     * @param str
     * @return
     */
    public static String getSHA256(String str){
        MessageDigest messageDigest;
        String encoder = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encoder = byte2Hex(messageDigest.digest());
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return encoder;
    }

    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        String temp = null;
        for (int i = 0; i<bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1 ){
                stringBuilder.append("0");
            }
            stringBuilder.append(temp);
        }
        return stringBuilder.toString();
    }

    public static String preIndex(LogEntry logEntry, String preIndexSha){

        return getSHA256(localSha(logEntry) + preIndexSha);
    }

    public static String localSha(LogEntry logEntry) {
        return getSHA256(getSHA256(Integer.toString(logEntry.getIndex()))+getSHA256(logEntry.getValue()));
    }
}
